<template>
  <view class="bg-white">
    <view v-if="showTitleBar" class="el-cu-bar">
      <view class="action">
        <text class="title-text" :style="titleStyle">{{ titleText }}</text>
      </view>
      <view v-if="isShowNumber" class="action">
        {{ imgList.length }}/{{ imgMaxCount }}
      </view>
    </view>
    <view class="cu-form-group">
      <view class="grid col-4 grid-square flex-sub">
        <view v-for="(item, index) in imgList" :key="index" class="bg-img" :data-url="item.imgUrl" @tap="ViewImage">
          <image :src="item.imgUrl" mode="aspectFill"></image>
          <view class="cu-tag bg-red" :data-index="index" @tap.stop="DelImg">
            <text class='cuIcon-close'></text>
          </view>
        </view>
        <!-- 添加图片 -->
        <view v-if="imgList.length < imgMaxCount" class="upload-box" @tap="ChooseImage">
          <text class='cuIcon-add'></text>
          <!-- <image class="upload-icon" src="/static/icons/icon-add-grey.svg" mode="" /> -->
        </view>
      </view>
    </view>
  </view>
</template>
<script setup lang="ts" >
/**
 * 基础ColorUI的选择图片组插件
 * @description  基于Color UI的选择图片组插件
 * @property {String} titleText 默认标题（默认值上传凭证）
 * @property {Boolean} showTitleBar 是否展示标题栏（默认值true）
 * @property {Number} imgMaxCount 最大上传图片数（默认10）
 * @event {Function()} change 修改图片后当前的图片组
 */
import configService from '@/config/config.service'
const { proxy } = getCurrentInstance() as any

const emit = defineEmits(['change'])
const props = withDefaults(defineProps<Props>(), {
  value: [],
  // 域前缀
  prefix: '/yst/aftersale',
  // 默认标题
  titleText: '上传凭证',
  // 是否展示标题栏
  showTitleBar: true,
  // 最大图片数
  imgMaxCount: 10,
  // 是否显示限制数量
  isShowNumber: false,
  // 标题栏样式
  titleStyle: null,
  isViewImage: false
})
interface Props {
  value?: any
  prefix?: string
  titleText?: string
  showTitleBar?: boolean
  imgMaxCount?: number
  titleStyle?: any
  isShowNumber?: boolean
  isViewImage?: boolean
}
const imgList = ref([] as any)

// 上传图片
const uploadImage = (filepath) => {
  console.log(filepath)
  proxy.$dialog.loading()
  uni.uploadFile({
    url: `${configService.apiUrl}${props.prefix}/com/file/v1/upload`,
    filePath: `${filepath}`,
    name: 'file',
    header: {
      'Content-Type': 'multipart/form-data',
      Authorization: uni.getStorageSync('Authorization')
    },
    success: (uploadFileRes) => {
      console.log('uploadFileRes', JSON.parse(uploadFileRes.data))
      const tempResp = JSON.parse(uploadFileRes.data)
      if (tempResp.success) {
        imgList.value.push({
          ...tempResp.data,
          imgUrl: `${configService.apiUrl}${props.prefix}/com/file/v1/${tempResp.data.fileCode}/download`
        })
        changeValue(imgList.value)
      } else {
        proxy.$dialog.toast(tempResp.msg)
      }
      proxy.$dialog.loaded()
    },
    fail: (err) => {
      proxy.$dialog.toast('上传失败，请重试')
      proxy.$dialog.loaded()
    }
  })
}

//保存 把当前的数据回调出去
const changeValue = (params) => {
  console.log(params)
  emit('change', params)
}

/**
 * 选择图片
 */
const ChooseImage = () => {
  uni.showActionSheet({
    itemList: ['相机', '从相册中选择'],
    success: (res) => {
      uni.chooseImage({
        count: 1, // 默认上传图片数
        sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
        sourceType: res.tapIndex === 1 ? ['album'] : ['camera'], //从相册选择
        success: (res) => {
          uploadImage(res.tempFilePaths)
        }
      })
    }
  })
}
/** 查看图片
 * @param {Object} e
 */
const ViewImage = (e) => {
  uni.previewImage({
    urls: imgList.value.map((item) => item.imgUrl),
    current: e.currentTarget.dataset.url
  })
}
/** 删除图片
 * @param {Object} e
 */
const DelImg = (e) => {
  uni.showModal({
    title: '提示',
    content: '确认要删除吗',
    cancelText: '取消',
    confirmText: '确认',
    success: async (res) => {
      if (res.confirm) {
        const tempIndex = e.currentTarget.dataset.index
        const tempFile = imgList.value[tempIndex]
        proxy.$dialog.loading()
        const respone = await proxy.$http.delete(`${props.prefix}/com/file/v1/${tempFile.fileCode}`)
        if (respone.success) {
          imgList.value.splice(e.currentTarget.dataset.index, 1)
          changeValue(imgList.value)
        } else {
          proxy.$dialog.toast(respone.msg)
        }
        proxy.$dialog.loaded()
      }
    }
  })
}
watch(props.value, (value, prevValue) => {
  imgList.value = value
})
watch(
  () => props.isViewImage,
  () => {
    imgList.value = []
  }
)
</script>
<style lang="scss" scoped>
.el-cu-bar {
  display: flex;
  position: relative;
  justify-content: space-between;
  align-items: center;
  padding: 32rpx;
}

.title-text {
  line-height: 40rpx;
  font-weight: 400;
  font-size: 28rpx;
  color: rgba(0, 0, 0, 0.6);
}

.upload-box {
  border-radius: 8rpx;
  background: #f8f8f8;
  // .upload-icon {
  //   width: 40rpx;
  //   height: 40rpx;
  // }
}
</style>
